/**
 * Copyright (2024, ) Institute of Software, Chinese Academy of Sciences
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.ac.iscas.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * It is used for creating various HttpRequest
 * 
 * @author wuheng@iscas.ac.cn
 * @since 1.0.0
 **/
public class JsonUtil {

	private JsonUtil() {
		super();
	}

	public static Iterator<Map.Entry<String, JsonNode>> iterator(JsonNode json) {
		return json.isObject() ? json.fields() : null;
	}

	public static Map<String, Object> values(Iterator<Map.Entry<String, JsonNode>> iter) {
		Map<String, Object> map = new HashMap<>();
		while (iter.hasNext()) {
			Map.Entry<String, JsonNode> field = iter.next();
			map.put(field.getKey(), field.getValue());
		}
		return map;
	}
	
	public static JsonNode getStream(HttpUriRequestBase http) throws Exception {
		try (CloseableHttpResponse response = HttpClients.createDefault().execute(http)) {
            
            // 获取响应状态码
            int statusCode = response.getCode();
            System.out.println("Response Status Code: " + statusCode);
            
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            
            if (entity != null) {
                // 将响应实体转换为字符串并打印
                return new ObjectMapper().readTree(entity.getContent());
            }
        }
		return null;
	}
}
